//
//  BusinessActivityVC.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/8/4.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

class BusinessActivityVC: BaseViewController {
    
    var hasmore = "-999"
    
    var page_total = "-999"
    
    var dataModels : [BusinessActivityModel]?
    
    var page = -999
    
    var isDiscover = false

    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = "商家活动"
        
        plainTableView.estimatedRowHeight = 100
        
        plainTableView.separatorStyle = .none
        
        plainTableView.tableFooterView = UIView()
        
        if isDiscover == true {
            
            plainTableView.contentInset = UIEdgeInsetsMake(ZMNavMaxY + ZMTitlesViewH, 0, 49, 0)
            
            
        }
        plainTableView.register(UINib(nibName: StringFromClass(classType: BusinesActivityCell.self), bundle: nil), forCellReuseIdentifier: BusinesActivityCell.identifer())
        
        weak var weakSelf = self
        
        plainTableView.mj_header =  ZMRefreshHeader.init {
            
            weakSelf!.loadData()
            
        }
        
        plainTableView.mj_header.beginRefreshing()
        
        plainTableView.mj_footer = ZMRefreshFooter.init{
            
            weakSelf!.loadMoreData()
            
        }
        

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

   
}

extension BusinessActivityVC{
    
    func loadData() {
        
        page = 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        
        
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=article&a=article_list&ac_id=1", parameters: parmeter) {[weak self] (responseObject, error) in
            
            
            if error == nil {
                
                self?.hasmore = responseObject!["hasmore"] as! String
                
                self?.page_total = responseObject!["page_total"] as! String
                
                self?.dataModels = [BusinessActivityModel]()
                
                
                
                for dic in responseObject!["datas"]!["article_list"] as! [[String : AnyObject]]{
                    
                    self!.dataModels!.append(BusinessActivityModel(dic: dic))
                    
                }
                
                
                
                
                if self!.dataModels!.count == 0{
                    
                    self?.showLogoView(text : "暂无商家活动...")
                    
                    self!.plainTableView.mj_header.endRefreshing()
                    
                }else{
                    
                    self!.cachePictures()
                    
                }
                
                
                
                
                
            }else{
                
                self!.plainTableView.mj_header.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
        }
        
        
    }
    
    
    
    
    
    
    
    
    func loadMoreData() {
        
        page += 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=article&a=article_list&ac_id=1", parameters: parmeter) {[weak self] (responseObject, error) in
            
            
            if error == nil {
                
                self?.hasmore = responseObject!["hasmore"] as! String
                
                self?.page_total = responseObject!["page_total"] as! String
                
                var tempArray = [BusinessActivityModel]()
                
                for dic in responseObject!["datas"]!["article_list"] as! [[String : AnyObject]]{
                    
                    let tempModel = BusinessActivityModel(dic: dic)
                    
                    tempArray.append(tempModel)
                    
                    self!.dataModels!.append(tempModel)
                    
                }
                
                
                self!.cacheMorePictures(model: tempArray)
                
                
                
                
                
            }else{
                
                self!.plainTableView.mj_footer.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
        }
        
    }
    
    
    
    
    func cachePictures(){
        
        
        let grop = DispatchGroup()
        
        for temp in dataModels! {
            
            guard let url = URL(string: temp.article_cover) else {
                continue
                
            }
            
            grop.enter()
            
            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
                
                //                QL1("下载一张完成")
                
                grop.leave()
                
            })
            
        }
        
        grop.notify(queue: DispatchQueue.main) {
            
            
            //            QL1("全部下载完成，刷新UI")
            
            self.plainTableView.mj_footer.resetNoMoreData()
            
            
            if self.hasmore == "0" {
                
                self.plainTableView.mj_footer.endRefreshingWithNoMoreData()
                
            }
            
            self.plainTableView.mj_header.endRefreshing()
            
            self.plainTableView.reloadData()
        }
        
    }
    
    
    func cacheMorePictures(model : [BusinessActivityModel]){
        
        
        let grop = DispatchGroup()
        
        for temp in model {
            
            guard let url = URL(string: temp.article_cover) else {
                continue
            }
            
            grop.enter()
            
            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
                grop.leave()
                
            })
            
        }
        
        
        grop.notify(queue: DispatchQueue.main) {
            
            if self.hasmore == "0" {
                
                self.plainTableView.mj_footer.endRefreshingWithNoMoreData()
                
                
            }else{
                
                self.plainTableView.mj_footer.endRefreshing()
                
            }
            
            
            
            self.plainTableView.reloadData()
            
        }
        
        
    }
    
    
    
    
    
}






extension BusinessActivityVC{
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        if dataModels == nil {
            return 0
        }
        
        if dataModels!.count > 0 {
            return 1
            
        } else {
            
            return 0
            
        }
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataModels?.count ?? 0
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        let tableCell : BusinesActivityCell =  tableView.dequeueReusableCell(withIdentifier: BusinesActivityCell.identifer()) as! BusinesActivityCell
        
        tableCell.model = dataModels?[indexPath.row]
        
        
        return tableCell
        
    }
    
    
    
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //        super.tableView(tableView, didSelectRowAt: indexPath)
        
        let model = dataModels?[indexPath.row]
        
        if model != nil {
            
            let temp = UpLoadIconController()
            
            temp.urlStr = model!.article_url
            
            
            navigationController?.pushViewController(temp, animated: true)
            
        }
        
        
        
    }
    
    
    
    
    
}
